<script setup>
import * as echarts from 'echarts';
import { ref, onMounted } from 'vue';

// 使用ref创建一个响应式引用，用于存储DOM元素
const chartDom = ref(null);

// 在组件挂载完成后初始化图表
onMounted(() => {
  // 确保DOM元素已经挂载
  const myChart = echarts.init(chartDom.value);
  
  const option = {
    xAxis: {
      type: 'category',
      data:getRecentMonths()
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [150, 230, 224, 220, 135, 0, 260],
        type: 'line'
      }
    ]
  };

  myChart.setOption(option);

  // 可选：在组件卸载时销毁图表，避免内存泄漏
  const cleanup = () => {
    myChart.dispose();
  };
  // 监听组件卸载生命周期，执行清理函数
  import.meta.env.MODE !== 'production' ? undefined : onUnmounted(cleanup);
});

const getRecentMonths = (monthCount = 6) => {
  const months = []
  const date = new Date()
  for (let i = monthCount - 1; i >= 0; i--) {
    const tempDate = new Date(date)
    tempDate.setMonth(date.getMonth() - i)
    months.push(
      `${tempDate.getFullYear()}-${String(tempDate.getMonth() + 1).padStart(2, '0')}`
    )
  }
  return months
}
</script>

<template>
  <div ref="chartDom" style="width: 600px; height: 400px;"></div>
</template>

<style scoped>
</style>